package com.minggo.charmword.fragment;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.minggo.charmword.R;
import com.minggo.charmword.activity.LoginActivity;
import com.minggo.charmword.activity.PlanActivity;
import com.minggo.charmword.bitmap.BitmapDisplayConfig;
import com.minggo.charmword.bitmap.FinalBitmap;
import com.minggo.charmword.cache.CacheUtils;
import com.minggo.charmword.logic.UpdateAvtarUtil;
import com.minggo.charmword.model.Result;
import com.minggo.charmword.model.User;
import com.minggo.charmword.service.CharmWordApplication;
import com.minggo.charmword.util.PhotoUtil;
import com.minggo.charmword.util.SharePreferenceUtil;
import com.minggo.charmword.util.UserUtil;
import com.minggo.charmword.view.WordDialog;
import com.minggo.charmword.view.WordDialog.OnDialogClickListener;

/**
 * 左边栏菜单
 * 
 * @author minggo
 * @time 2014-8-28 S下午10:29:06
 */
public class FragmentUserCenter extends Fragment implements OnClickListener {

	private Activity activity;
	private View mainView;
	private ImageView avasterIv;
	public static final int REQUEST_LOGIN = 10001;
	private User user;
	private Gson gson = new Gson();
	private TextView userNameTv;
	private WordDialog imageDialog;// 弹出拍照选择
	public static final int GET_USER_CAMERA = 10003;// 拍照
	public static final int GET_USER_GALLERY = 10002;// 本地
	private FinalBitmap fb;
	private BitmapDisplayConfig bitmapDisplayConfig;// 注册一个加载图片的默认配置
	
	private Button exitBt;
	private Button planBt;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.fragment_user_center, container, false);
		initUI();
		requestData();
		return mainView;
	}

	/**
	 * 初始化UI
	 */
	private void initUI() {
		avasterIv = (ImageView) mainView.findViewById(R.id.iv_avater);
		userNameTv = (TextView) mainView.findViewById(R.id.tv_username);
		exitBt = (Button) mainView.findViewById(R.id.bt_exit);
		planBt = (Button) mainView.findViewById(R.id.bt_learn_plan);
		
		fb = FinalBitmap.create(activity);

		bitmapDisplayConfig = new BitmapDisplayConfig();
		bitmapDisplayConfig.setAnimation(null);
		bitmapDisplayConfig.setAnimationType(BitmapDisplayConfig.AnimationType.fadeIn);
		bitmapDisplayConfig.setLoadingBitmap(BitmapFactory.decodeResource(activity.getResources(), R.drawable.img_avatar_default));
		bitmapDisplayConfig.setLoadfailBitmap(BitmapFactory.decodeResource(activity.getResources(), R.drawable.img_avatar_default));
		
		
		avasterIv.setOnClickListener(this);
		exitBt.setOnClickListener(this);
		planBt.setOnClickListener(this);
	}

	public void requestData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				user = gson.fromJson(CacheUtils.getInstance().getDiskCache("user_info"), User.class);
				
				if (user!=null) {
					CharmWordApplication.getInstance().user = user;
				}
				handler.sendEmptyMessage(1000);

			}
		}).start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		fb.clearMemeoryCache();
	}
	
	private Handler handler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 1000:// 刷新用户
				refreshUI();
				break;
			case UpdateAvtarUtil.AVTAR_SUCCESS:
				if (msg.obj != null) {
					Result result = (Result) msg.obj;
					if (result.success) {
						Toast toast = Toast.makeText(activity, result.content, Toast.LENGTH_LONG);
						toast.show();
						
					} else {
						Toast toast = Toast.makeText(activity, result.errorMsg, Toast.LENGTH_LONG);
						toast.show();
					}
				}
				break;
			default:
				break;
			}
			return false;
		}
	});

	private void refreshUI() {
		if (UserUtil.getFirstUser(activity)!=null) {
			Toast.makeText(activity, UserUtil.getFirstUser(activity).username, Toast.LENGTH_LONG).show();
			//Toast.makeText(activity, UserUtil.getTest(activity).name+"", Toast.LENGTH_LONG).show();
			
		}
		if (user != null) {
			userNameTv.setText(user.username);
			user.type = 1;
			//fb.display(avasterIv, user.avatar);
			fb.displayRound(avasterIv, user.avatar, bitmapDisplayConfig, true);
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					UserUtil.saveUser(activity, user);
				}
			}).start();
			
		}else{
			fb.clearMemeoryCache();
			avasterIv.setImageResource(R.drawable.img_avatar_default);
			userNameTv.setText("请登录");
		}

	}
	
	

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_avater:
			if (user==null) {
				activity.startActivityForResult(new Intent(activity, LoginActivity.class), REQUEST_LOGIN);
			}else{
				btnUploadPicture(v);
			}
			break;
		case R.id.bt_exit:
			
			CacheUtils.getInstance().removeDiskCache("user_info");
			user = null;
			refreshUI();
			break;
		case R.id.bt_learn_plan:
			Intent intent = new Intent(activity, PlanActivity.class);
			intent.putExtra("from", "usercenter");
			activity.startActivity(intent);
			break;
		default:
			break;
		}
	}

	/**
	 * 点击拍照按钮处理事件
	 */
	public void btnUploadPicture(View view) {
		if (PhotoUtil.isSDCardReady()) {
			// 如果目录不存在就建立新的目录
			String dir = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword";
			File dirFile = new File(dir);
			if (!dirFile.exists() && !dirFile.mkdir()) {

			}
			String imgDir = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword/user";
			File imgFile = new File(imgDir);
			if (!imgFile.exists() && !imgFile.mkdir()) {
			}
			String imagesDir = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword/user/images";
			File imagesFile = new File(imagesDir);
			if (!imagesFile.exists() && !imagesFile.mkdir()) {
				
			}
			OnDialogClickListener dialogClickListener = new OnDialogClickListener() {

				@Override
				public void onDialogClick(int state) {
					String imagePath = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword/user/images/" + System.currentTimeMillis() + ".jpg";
					
					SharePreferenceUtil.saveUserAvatar(activity, imagePath);
					//AppConfig.getAppConfig(activity).setPref("avtarO", imagePath);
					if (state == WordDialog.SELECT_CAMERA_PICTURE) {
						imageDialog.dismiss();

						PackageManager packageManager = activity.getPackageManager();
						boolean doesHaveCamera = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);
						if (doesHaveCamera) {
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imagePath)));
							activity.startActivityForResult(intent, GET_USER_CAMERA);
						} else {
							Toast.makeText(activity, "没有合适的相机应用程序", Toast.LENGTH_LONG).show();
						}
					} else if (state == WordDialog.SELECT_LOCAL_PICTURE) {
						imageDialog.dismiss();
						Intent intent = new Intent();
						/* 开启Pictures画面Type设定为image */
						intent.setType("image/*");
						/* 使用Intent.ACTION_GET_CONTENT这个Action */
						intent.setAction(Intent.ACTION_GET_CONTENT);
						/* 取得相片后返回本画面 */
						activity.startActivityForResult(intent, GET_USER_GALLERY);
					}
				}
			};
			// 声明一个弹出框
			imageDialog = new WordDialog(activity, R.style.select_dialog, WordDialog.UPLOAD_AVATAR_DIALOG, "选择头像",
				 dialogClickListener);
			imageDialog.setCanceledOnTouchOutside(true);
			imageDialog.show();

		} else {
			Toast.makeText(activity, "SD卡不存在，请检查你的sd卡", Toast.LENGTH_SHORT).show();
		}

	}
	
	/**
	 * 设置头像
	 */
	public void setAvatar() {
		if (user!=null) {
			String path = SharePreferenceUtil.getStringr(activity, user.userId+"avatar");
			if (!path.equals("")) {
				fb.displayRound(avasterIv, path, bitmapDisplayConfig, true);				
				user.avatar = path;
				UserUtil.saveUser(activity, user);
				try {
					CacheUtils.getInstance().setDiskCache("user_info", new Gson().toJson(user));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			File file = new File(path);
			if (file.exists()) {
				UpdateAvtarUtil avtarUtil = new UpdateAvtarUtil(activity, handler, user.userId+"", file);
				avtarUtil.execute();
			}
			//refreshUI();
		}
	}
	
	@Override
	public void onDetach() {
		super.onDetach();
		activity = null;
	}
}
